<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\Orderinfo;


class VirtualController extends Controller
{
    public function actionIndex(){
        $store = Yii::$app->request->get("store","rubberstore");

        if ($store == "rubberstore"){
            return $this->render("rubberstore");
        }else{
            return $this->render("mouldstore");
        }
    }

    public function actionBoxdetail(){
        $store = Yii::$app->request->get("store","rubberstore");
        $location = Yii::$app->request->get("location","1-1-1");


        $query = new \yii\db\Query();

        $inventoryList = $query->select("*")->from("JXC_INVENTORY")->where("POSITION = '".$location."'")->all();

        $result = array();
        foreach($inventoryList as $inventoryItem){
            $tempresult = $inventoryItem;
            $tempresult['COSTPRICE'] = "";
            $tempresult['SELLINGPRICE'] = "";

            $productid = $inventoryItem['PRODUCTID'];

            if (!empty($productid)){
                $productInfo = $query->select("*")->from("JXC_PRODUCT")->where("PRODUCTID = ".$productid)->one();

                if (!empty($productInfo)){
                    $tempresult['COSTPRICE'] = $productInfo['COSTPRICE'];
                    $tempresult['SELLINGPRICE'] = $productInfo['SELLINGPRICE'];
                }
            }

            $result[] = $tempresult;
        }

        return $this->render("boxdetail", ['list' => $result, 'position' => $location]);
    }

    public function actionBoxlocation(){
        if(Yii::$app->request->isAjax){
            $queryitem = Yii::$app->request->get("queryitem");

            $result = $this->getLocationByQueryItem($queryitem);
            return $result;
        }
    }

    public function getLocationByQueryItem($queryitem){

        $query = new \yii\db\Query();
        $inventoryList = array();

        if (empty($queryitem)){
            $inventoryList = $query->select("POSITION")->from("JXC_INVENTORY")->where("INVENTORYID = 1")->all();
        }else{
            $inventoryList = $query->select("POSITION")->from("JXC_INVENTORY")->where("DRAWINGNO like '%".$queryitem."%'")->distinct(true)->all();
        }
        return $this->fetch_box_locations($inventoryList);
    }

    public function fetch_box_locations($inventoryList){
        $array_boxlocationlist = array();

        foreach($inventoryList as $inventoryItem){
            $box_location = array();

            $position = $inventoryItem['POSITION'];
            if (!empty($position)){
                $var = explode("-", $position);

                if (count($var) > 2){
                    if (is_numeric($var[0]) && is_numeric($var[1]) && is_numeric($var[2])){
                        $array_boxlocationlist[] = $position;
                    }
                }
            }
        }

        return json_encode($array_boxlocationlist, JSON_UNESCAPED_UNICODE);
    }
}